/**
 * @module websocket-handler
 * @description 收到消息，关闭连接等回调函数
 */

const { resolve, dirname } = require("path");

const { FfmpegManager } = require("./ffmpeg");
const { cacheDir, COMMANDS } = require("../config");
const { useCommandHandlers } = require("../lib/useCommandHandlers");
const { ClientManager } = require("./clientManager");
const { deleteDirectory, md5 } = require("./util");

// 客户端连接管理
const clientManager = new ClientManager();
// ffmpeg进程管理
const ffmpegManager = new FfmpegManager({
  cachePath: resolve(__dirname, "..", cacheDir),
  onError(output, rtsp) {
    console.log("出错啦 output", output);
    console.log("出错啦 rtsp", rtsp);
    console.log("md5", md5(rtsp));

    const m3u8DirPath = dirname(output);
    console.log("🚀 ~ m3u8DirPath:", m3u8DirPath);

    // 删除目录
    deleteDirectory(m3u8DirPath, true);

    // 删除该client的rtsp
    clientManager.removeRtsp(null, rtsp);

    console.log("Catch Error.clientMap", clientManager.clientMap);
  },
});

// 【命令】：方法映射
const commandHandles = {
  [COMMANDS.START]: startCommand,
  [COMMANDS.STOP]: stopCommand,
};

const command = useCommandHandlers(commandHandles);

// console.log("path", resolve(__dirname, "..", cacheDir));

/**
 *  收到消息的回调
 *
 * @param {object} socket - socket对象
 * @param {string} message - 消息字符串
 */
const onMessage = (message, socket, request) => {
  console.log("收到客户端消息：", message);
  command(message, socket, request);
};

/**
 * 断开连接的回调
 */
const onClose = (error, socket, request) => {
  console.log("客户端断开连接", request.clientId);
  clientManager.removeById(request.clientId);
  removeRtspHandler();
};

/**
 * 启动转换rtsp流服务
 * @param {string[]} rtsps
 * @param {object} socket
 * @param {object} request
 * @returns {string} hls URL
 */
function startCommand(rtsps, socket, request) {
  console.log("startCommand");

  const urls = rtsps.map((rtsp) => ffmpegManager.create(rtsp));
  clientManager.add(request.clientId, rtsps);

  socket.send(JSON.stringify(urls));

  console.log("clientManager.clientMap", clientManager.clientMap);
  console.log("ffmpegManager.ffmpegMap", ffmpegManager.ffmpegMap);
}

/**
 * 停止转换流服务
 * @param {string[]} rtsps
 * @param {object} socket
 * @param {object} request
 */
function stopCommand(rtsps, socket, request) {
  console.log("stopCommand", rtsps);
  clientManager.removeRtsp(request.clientId, rtsps);

  removeRtspHandler();
}

function removeRtspHandler() {
  const nowRtsps = clientManager.getAllRtsp();
  const allRtsps = ffmpegManager.getAllRtsp();

  console.log("🚀 ~ file: nowRtsps:", nowRtsps);
  console.log("🚀 ~ file: allRtsps:", allRtsps);

  // 获取差集
  const beRemovedRtsps = allRtsps.filter((r) => !nowRtsps.includes(r));
  console.log("🚀 ~ 差集:", beRemovedRtsps);
  ffmpegManager.stop(beRemovedRtsps);
}

module.exports = {
  onMessage,
  onClose,
};
